当前位置: 首页 > 工具软件 > Plot Drawing > 使用案例 >

matlab画array,c#实现matlab的数组plot功能

司徒钱青
2023-12-01

新建一个Form1,写入下面代码,并在Form1添加一个print事件,Form1_Paint。Form1_Paint中有一个随机数二维数组 twoDim,把他改成你想要输出的数组。即可在Form1像matlab plot一样画出二维数组。

原理:

通过调用

e.Graphics.DrawLine作图

并通过Color MapRainbowColor方法定义不同数值对应的颜色

对数组遍历后画出数组的彩色图

但是注意,在c#中这样做需要执行遍历语句多次,作图的效率很低!!

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace COLORMAP

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

// Draw rainbow colors on the form.

private void Form1_Paint(object sender, PaintEventArgs e)

{

Random r = new Random();

float[,] twoDim = new float[100, 100];

for (int i = twoDim.GetLowerBound(0); i <= twoDim.GetUpperBound(0); i++)

{

for (int j = twoDim.GetLowerBound(1); j <= twoDim.GetUpperBound(1); j++)

{

twoDim[i, j] = r.Next(1, 100);

}

}

int Panel_Width = this.panel1.Width;

int Panel_height = this.panel1.Height;

double Pixel_Width = Panel_Width / (twoDim.GetUpperBound(0) - twoDim.GetLowerBound(0) + 1);

double Pixel_height = Panel_height / (twoDim.GetUpperBound(1) - twoDim.GetLowerBound(1) + 1);

int Pixel_Wid = Convert.ToInt32(Math.Floor(Pixel_Width));

int Pixel_heig = Convert.ToInt32(Math.Floor(Pixel_height));

for (int i = twoDim.GetLowerBound(0); i <= twoDim.GetUpperBound(0); i++)

{

for (int j = twoDim.GetLowerBound(1); j <= twoDim.GetUpperBound(1); j++)

{

using (Pen the_pen = new Pen(MapRainbowColor(twoDim[i, j], 0, 100)))

{

for (int x = i*Pixel_Wid; x <= (i + 1) * Pixel_Wid; x++)

{

e.Graphics.DrawLine(the_pen, x, j * Pixel_heig, x, (j + 1) * Pixel_heig);

}

}

}

}

}

// Map a value to a rainbow color.

private Color MapRainbowColor(

float value, float red_value, float blue_value)

{

// Convert into a value between 0 and 1023.

int int_value = (int)(1023 * (value - red_value) /

(blue_value - red_value));

// Map different color bands.

if (int_value < 256)

{

// Red to yellow. (255, 0, 0) to (255, 255, 0).

return Color.FromArgb(255, int_value, 0);

}

else if (int_value < 512)

{

// Yellow to green. (255, 255, 0) to (0, 255, 0).

int_value -= 256;

return Color.FromArgb(255 - int_value, 255, 0);

}

else if (int_value < 768)

{

// Green to aqua. (0, 255, 0) to (0, 255, 255).

int_value -= 512;

return Color.FromArgb(0, 255, int_value);

}

else

{

// Aqua to blue. (0, 255, 255) to (0, 0, 255).

int_value -= 768;

return Color.FromArgb(0, 255 - int_value, 255);

}

}

}

}

标签:plot,twoDim,c#,System,Paint,Form1,matlab,数组,using

来源: https://blog.csdn.net/weixin_44216944/article/details/112852962

 类似资料: